const { equal } = require('assert');
const { watch } = require('fs');
const { join, extname } = require('path');

class Watch {
  constructor(config) {
    this.config = config
    this.changeSubscribeList = []
    const watchPath = this.config.getValue('watch-path')
    const startPath = this.config.getValue('start-path')
    this.watchPath = join(startPath, watchPath)
  }

  start () {
    const params = { encoding: 'utf8', persistent: true, recursive: true }

    watch(this.watchPath, params, (event, filename) => {
      if (event === 'change') {
        this.change(filename)
      }
    })
    return this
  }

  onchange (listener) {
    equal(typeof listener, 'function', `listener must be of type function! cannot be a [${typeof listener}]!`)
    this.changeSubscribeList.push(listener)
    return this
  }

  change (filename) {
    const suffix = extname(filename)
    const suffixBlacklist = this.config.getValue('suffix-blacklist')
    if (suffixBlacklist.includes(suffix)) return

    const allPath = join(this.watchPath, filename)
    const pathBlacklist = this.config.getValue('path-blacklist').map(path => join(this.watchPath, path))
    if (pathBlacklist.some(item => allPath.includes(item))) return
    console.log('检测到文件变动:', allPath);
    this.changeSubscribeList.forEach(listener => listener())
  }
}

module.exports = Watch